﻿/*
 *  Copyright (c) 2009 - 2010 CoolCode
 *  
 *  Developer：Bruce Lee 
 *  Created Date: 2010-07-27 
 *  Modified Date:  
 *  Revision: 1.0.0.0 
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web.Mvc;
using CoolCode;

namespace CoolCode.Web.Mvc.UI
{
	public class DomBuilder : StringWriter
	{
		private Stack<TagBuilder> _tags = new Stack<TagBuilder>();
		private string _innerHtml = string.Empty;

		public DomBuilder()
		{
		}

		public TagBuilder CreateTag(string tagName)
		{
			TagBuilder tagBuilder = new TagBuilder(tagName);
			_tags.Push(tagBuilder);
			return tagBuilder;
		}

		public override void Write(string value)
		{
			if (_tags.Count == 0)
			{
				_innerHtml += WrapChildrenHtml(value);
			}
			TagBuilder tagBuilder = _tags.Peek();
			tagBuilder.InnerHtml += WrapChildrenHtml(value);
		}

		public void EndTag()
		{
			if (_tags.Count == 0)
				throw new Exception("Begin Tag Not Found!");

			TagBuilder tagBuilder = _tags.Pop();
			_innerHtml = tagBuilder.ToString();

			if (_tags.Count == 0)
				return;

			_tags.Peek().InnerHtml += WrapChildrenHtml(_innerHtml);
		}

		private string WrapChildrenHtml(string html)
		{
			return html;
			//StringBuilder sb = new StringBuilder();
			//sb.Append("\r\n");
			//sb.Append("\t".Repeat(_tags.Count + 1));
			//sb.Append(html);
			//sb.Append("\r\n");
			//return sb.ToString();
		}

		public override string ToString()
		{
			//if (_tags.Count == 0)
			//{
			//    return _innerHtml;
			//}
			Stack<TagBuilder> copyTags = new Stack<TagBuilder>(_tags);
			while (copyTags.Count > 0)
			{
				TagBuilder tagBuilder = copyTags.Pop();

				if (copyTags.Count == 0)
				{
					return tagBuilder.ToString();
				}

				copyTags.Peek().InnerHtml += tagBuilder.ToString();
			}

			return _innerHtml;
		}
	}
}
